/***************************************************************************
 *   Copyleft 2008-2009 by												   *
 *	 Iwanicki Krzysztof													   *
 *   <gamma.mini.pw.edu.pl/~iwanickik>									   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 ***************************************************************************/
#include "./vWin32Timer.h"
#include <mmsystem.h>

namespace Vendetta {
	vWin32Timer::vWin32Timer() {
		mStartTime = timeGetTime();
	}

	vWin32Timer::~vWin32Timer() {
	}

	vVoid vWin32Timer::Update() {
		mPrevPerFrameTime	= mPerFrameTime;
		mPerFrameTime		= vInt(timeGetTime() - mStartTime);
		mFrameTime			= (mPerFrameTime - mPrevPerFrameTime);

		mPrevFrameTimes[mFramesCounter % NUM_FPS_FRAMES] = (vReal) mPerFrameTime;

		// Refresh mFPS (at most 10 times per second)
		if (mPerFrameTime - mLastFPSRefreshTime > 100) {

			const vReal sumFrameTimes = mPrevFrameTimes[mFramesCounter % NUM_FPS_FRAMES] - mPrevFrameTimes[(mFramesCounter + 1) % NUM_FPS_FRAMES];

			const vReal approxFrameTime	= sumFrameTimes / (NUM_FPS_FRAMES - 1) * 0.001f;
			mFPS								= (approxFrameTime > 0) ? (1 / approxFrameTime) : 0;
			mLastFPSRefreshTime				= mPerFrameTime;
			
			// TEST
			//mFPS = (mFramesCounter * 1000.0f) / (timeGetTime() - mStartTime + 1);
		}

		mFramesCounter++;
	}

	vInt vWin32Timer::CurrentTime() const {
		return timeGetTime() - mStartTime;
	}
}